package com.draw.server.service;

import java.util.List;

import javax.jws.WebService;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.draw.core.Drawing;
import com.draw.core.Line;
import com.draw.core.User;
import com.draw.core.Vector;
import com.draw.server.hibernate.HibernateUtil;
import com.draw.webinterface.DrawingInterface;

@SuppressWarnings("unchecked")
@WebService(targetNamespace = "http://draw.some.com/", serviceName = "DrawingService", name = "DrawingService")
public class DrawingService implements DrawingInterface {
	private static final Logger logger = LoggerFactory
			.getLogger(DrawingService.class);

	@Override
	public void addDraw(Drawing drawing) {
		logger.info("Saving Drawing {}", drawing);
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		drawing.populate();
		session.save(drawing);
		for (Line line : drawing.getLines()) {
			session.save(line);
			for ( Vector vector : line.getVectors() ) {
				session.save(vector.getSource());
				session.save(vector.getDestination());
				session.save(vector);
			}
		}
		tx.commit();
	}

	@Override
	public List<Drawing> getDrawingReceived(User user) {
		Session session = HibernateUtil.getSession();
		String req = "from com.draw.core.Drawing where destination = :destination and done = :done";
		Query query = session.createQuery(req);
		query.setParameter("destination", user);
		query.setBoolean("done", false);
		List<Drawing> ld = query.list();
		for(Drawing d: ld) {
			d.unpopulate();
		}
		return ld;
	}

	@Override
	public List<Drawing> getDrawingSent(User user) {
		Session session = HibernateUtil.getSession();
		String req = "from com.draw.core.Drawing where source = :source and done = :done";
		Query query = session.createQuery(req);
		query.setParameter("source", user);
		query.setBoolean("done", false);
		List<Drawing> ld = query.list();
		for(Drawing d: ld) {
			d.unpopulate();
		}
		return ld;
	}

	@Override
	public void updateDraw(Drawing drawing) {
		logger.info("Update Drawing {}", drawing);
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		session.update(drawing);
		tx.commit();
	}

}
